<!--
 * @Description: 项目动态履约信息
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-09-26 16:40:56
 * @LastEditTime: 2022-10-28 15:50:54
 * @FilePath: \cscec-pms-admin\src\views\project\projectDynamicInformation\components\PerformanceInformation.vue
-->
<template>
  <div>
    <a-spin :spinning="loading">
      <custom-form
        ref="form"
        :is-validate="true"
        :edit-model="''"
        :rules="rules"
        :form="form"
        :form-list="formOption"
        @change="handleChange"
      >
        <template #forecastFinishMonth>
          <a-select
            v-model="form.forecastFinishMonth"
            :placeholder="pageType == 'update' ? '请选择' : ''"
            option-label-prop="label"
            :disabled="formOption.filter((v) => v.keyName === 'forecastFinishMonth')[0].disabled"
          >
            <a-select-option
              v-for="(item, index) in formOption.filter((v) => v.keyName === 'forecastFinishMonth')[0].data"
              :value="item.value"
              :label="item.value"
              :key="index"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </template>
        <template #forecastFinishYear>
          <a-date-picker
            format="YYYY"
            :placeholder="pageType == 'update' ? '请选择日期' : ''"
            mode="year"
            :open="yearShowOne"
            v-model="form.forecastFinishYear"
            @openChange="openChangeOne"
            :disabled="formOption.filter((v) => v.keyName === 'forecastFinishYear')[0].disabled"
            @panelChange="handlePanelChange"
          />
        </template>
      </custom-form>
    </a-spin>
    <!-- 选择审批人 -->
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
    <!-- 选择审批人 -->
  </div>
</template>
<script>
import { formList, updataList1, updataList2 } from '../model.js'
import cloneDeep from 'lodash.clonedeep'
import projectDynamicInformation from '@/api/projectDynamicInformation'
import qs from 'qs'
import mixins from '../mixins'
import moment from 'moment'
export default {
  name: 'PerformanceInformaion',
  mixins: [mixins],
  props: {
    // 提交中
    submiting: {
      type: Boolean,
      require: true
    },
    projectId: {
      type: String,
      default: ''
    }
  },
  components: {},
  data() {
    return {
      // 表单
      form: {},
      // 表单加载
      loading: true,
      yearShowOne: false,
      // 表单列表
      formList: cloneDeep(formList),
      // 编辑列表（0：非专业项目，1：专业项目）
      updataList: [],
      // 详情接口数据
      detail: {},
      isProSubProject: 0,
      pageType: 'update', // 页面类型
      // 流程配置
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      // 业务id
      businessId: null
    }
  },
  computed: {
    // 在建建筑面积标签文字
    engineeringMetersLabel() {
      let text = '在建建筑面积万m²'
      if (this.form.projectTypeCode === '638571526815358976' || this.form.projectTypeCode === '638571399132356608') {
        // 当项目类型为房建或其他时
        text = '在建建筑面积万m²'
      }
      if (this.form.projectTypeCode === '638571485077839872') {
        // 当项目类型为线性基础设施时
        text = '在施工程里程km'
      }
      return text
    },
    // 表单配置
    formOption() {
      // 编辑项
      const list = this.updataList
      // 表单项
      let option = []
      option = this.formList
        .map((el) => {
          if (el.visible !== false) {
            // 设置建筑面积的标签名
            if (el.keyName === 'totalArea') {
              el.label = this.engineeringMetersLabel
            }
            // 查看
            if (this.pageType === 'detail') {
              el.disabled = true
              el.placeholder = ' '
              if (el.title !== undefined || el.slot) {
                // 标题或者插槽
                return el
              } else {
                const index = list.findIndex((item) => el.keyName === item.keyName)
                if (index > -1) {
                  const obj = cloneDeep(list[index])
                  obj.placeholder = ' '
                  obj.disabled = true
                  return obj
                }
                if (el.type === undefined) {
                  // 没有指定类型
                  el.type = 'BaseInput'
                  // 专业项目的 形象 是input框 处理下
                  if (this.isProSubProject == 1 && el.keyName === 'imageProgressId') {
                    el.keyName = 'imageProgressName'
                    return el
                  }
                  return el
                } else {
                  return el
                }
              }
            }
            // 编辑
            if (this.pageType === 'update') {
              const index = list.findIndex((item) => el.keyName === item.keyName)
              if (index > -1) {
                const obj = cloneDeep(list[index])
                if (el.disabled) {
                  obj.disabled = true
                  // 变为禁用时手动修改了表单值(没能触发表单change事件)
                  this.form[list[index].keyName] = ''
                  obj.type = 'BaseInput'
                  delete obj.rules
                } else {
                  obj.disabled = false
                  // 变更后开工日期
                  if (obj.keyName === 'changeAfterStartTime') {
                    obj.attrs.disabledDate = (current) => {
                      return current && current > moment(this.form.changeAfterFinishDate).endOf('day')
                    }
                  }
                  // 实际竣工日期
                  if (obj.keyName === 'actualFinishDate') {
                    obj.attrs.disabledDate = (current) => {
                      return current && (current < moment(this.form.actualStartTime).endOf('day') || current >= moment(moment(this.form.monthlyDate).subtract(-1, 'month').format('YYYY-MM')))
                    }
                  }
                }
                if(obj.keyName === 'projectStatus') obj.disabled = true
                // 修改项
                return obj
              } else {
                // 禁用项
                el.disabled = true
                if (el.title !== undefined || el.slot) {
                  // 标题或者插槽
                  return el
                } else {
                  if (el.type === undefined) {
                    // 没有指定类型
                    el.type = 'BaseInput'
                    // 专业项目的 形象 是input框 处理下
                    if (this.isProSubProject == 1 && el.keyName === 'imageProgressId') {
                      el.keyName = 'imageProgressName'
                      return el
                    }
                    return el
                  } else {
                    return el
                  }
                }
              }
            }
          } else {
            return null
          }
        })
        .filter((el) => el !== null)
      return option
    },
    // 校验
    rules: {
      get: function () {
        const obj = {}
        this.formOption.map((item) => {
          if (item.rules) {
            obj[item.keyName] = item.rules
          }
        })
        return obj
      }
    }
  },
  async mounted() {
    await this.getDetail()
    await this.getPreposition()
    this.loading = false
  },
  async created() {
    const detailUrl = this.$route.query.detailUrl
    // 审批过来的
    if (detailUrl) {
      // 处理detailUrl 数据
      // 审批页面
      const handlerdetailUrl = decodeURIComponent(detailUrl)
      const arr = handlerdetailUrl.slice(handlerdetailUrl.indexOf('?') + 1).split('amp;')
      if (arr[0] === 'isProSubProject=0') {
        this.isProSubProject = 0
        this.updataList = cloneDeep(updataList1)
      } else {
        this.isProSubProject = 1
        this.updataList = cloneDeep(updataList2)
      }
      this.pageType = 'detail'
    } else {
      // 已审批-查看详情
      if (this.$route.query.type === 'approve') {
        const { isProSubProject } = this.$route.query
        if (isProSubProject ?? '' !== '') {
          this.isProSubProject = Number(isProSubProject)
          this.updataList = this.isProSubProject == 1 ? cloneDeep(updataList2) : cloneDeep(updataList1)
          this.pageType = 'detail'
          return
        }
        return
      }
      this.pageType = this.$route.query.pageType
      this.isProSubProject = this.$route.query.isProSubProject
      this.updataList = this.isProSubProject == 1 ? cloneDeep(updataList2) : cloneDeep(updataList1)
    }
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('project_dynamic')
  },
  methods: {
    getQueryVariable(variable) {
      var query = decodeURIComponent(location.search).substring(1)
      var vars = query.split('&')
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=')
        if (pair[0] == variable) {
          return pair[1]
        }
      }
      return false
    },
    openChangeOne(status) {
      //status是打开或关闭的状态
      this.yearShowOne = !this.yearShowOne
    },
    handlePanelChange(val) {
      this.form['forecastFinishYear'] = val
      this.yearShowOne = !this.yearShowOne
      this.$refs.form.$refs.ruleForm.clearValidate('forecastFinishYear')
    },
    /**
     * @description: 获取前置数据
     * @param {void}
     * @return {void}
     */
    async getPreposition() {
      const { code, data } = await projectDynamicInformation.planLabel(qs.parse({ types: '43,6,39,7', pageNo: 1, pageSize: 1000 }))
      if (code === 200) {
        const imageProgressId = []
        const creativeLevelId = []
        const meritContentId = []
        const observingLevelId = []
        data.forEach((el) => {
          // 形象进度
          if (el.type === '43') {
            imageProgressId.push({
              label: el.name,
              value: el.id
            })
          }
          // 已组织创优级别
          if (el.type === '6') {
            creativeLevelId.push({
              label: el.name,
              value: el.id
            })
          }
          // 已组织创优级别
          if (el.type === '39') {
            meritContentId.push({
              label: el.name,
              value: el.id
            })
          }
          // 已组织观摩级别
          if (el.type === '7') {
            observingLevelId.push({
              label: el.name,
              value: el.id
            })
          }
        })
        // 非专业的 形象进度 是select 专业的就是默认的不需要data
        if (this.isProSubProject == 0) {
          this.updataList[this.updataList.findIndex((el) => el.keyName === 'imageProgressId')].data = imageProgressId
        }
        this.updataList[this.updataList.findIndex((el) => el.keyName === 'creativeLevelId')].data = creativeLevelId
        this.updataList[this.updataList.findIndex((el) => el.keyName === 'meritContentId')].data = meritContentId
        this.updataList[this.updataList.findIndex((el) => el.keyName === 'observingLevelId')].data = observingLevelId
        return Promise.resolve()
      } else {
        return Promise.reject()
      }
    },
    /**
     * @description: 获取详情
     * @param {void}
     * @return {void}
     */
    async getDetail() {
      const detail = await projectDynamicInformation.detail({ id: this.$route.query.id })
      if (detail.code === 200) {
        // 编辑时去查询最新的项目状态
        if (this.pageType === 'update') {
          // 项目状态
          if (detail.data.projectOverviewVO && !detail.data.projectOverviewVO.projectStatus) {
            const {
              data: { projectStatusCode }
            } = await projectDynamicInformation.status({ projectId: detail.data.projectOverviewVO.projectId })
            detail.data.projectOverviewVO.projectStatus = projectStatusCode
          }
        }
        try {
          this.$emit('update:projectId', detail.data.projectOverviewVO.projectId)
        } catch (error) {}

        // 记录
        this.detail = detail.data
        // 写入表单
        let projectOverviewVO = detail.data.projectOverviewVO
        let projectDurationVO = detail.data.projectDurationVO
        let completionExpenseVO = detail.data.completionExpenseVO
        let contractAmountConditionVO = detail.data.contractAmountConditionVO
        if (!projectOverviewVO) {
          projectOverviewVO = {}
        }
        if (!projectDurationVO) {
          projectDurationVO = {}
        }
        if (!completionExpenseVO) {
          completionExpenseVO = {}
        }
        if (!contractAmountConditionVO) {
          contractAmountConditionVO = {}
        }
        // 处理服务端回显 select 下发的null 不显示提示语
        !projectOverviewVO.imageProgressId && (projectOverviewVO.imageProgressId = undefined)
        !projectOverviewVO.creativeLevelId && (projectOverviewVO.creativeLevelId = undefined)
        !projectOverviewVO.meritContentId && (projectOverviewVO.meritContentId = undefined)
        !projectOverviewVO.observingLevelId && (projectOverviewVO.observingLevelId = undefined)
        !projectDurationVO.forecastFinishMonth && (projectDurationVO.forecastFinishMonth = undefined)
        projectOverviewVO.totalArea = projectOverviewVO.totalArea ? projectOverviewVO.totalArea.toFixed(2) : ''
        // 如果是专业项 项目开工令/开工报告 下达的文件 不可以修改
        if (this.isProSubProject == 1) {
          projectDurationVO.startWorkReportsFileList.map((v) => {
            v.isHidden = true
          })
        }
        
        
        this.form = Object.assign({}, this.form, projectOverviewVO, projectDurationVO, completionExpenseVO, contractAmountConditionVO)
        // 遍历表单适应所有关联项
        for (const item in this.form) {
          this.handleChange(item, this.form[item])
        }
        let flag = this.pageType === 'detail' ? true : false
        // 填报人
        this.form.fillPersonName = flag ? detail.data.fillPersonName : JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.name
        // 填报日期
        this.form.fillDate = flag ? detail.data.fillDate : moment().format('YYYY-MM-DD')
        const index = this.formList.findIndex((el) => el.keyName === 'startWorkReportsFileList')
        if(!projectDurationVO.changeAfterStartTimeLastMonth) {
          if(projectDurationVO.contractStartDate != projectDurationVO.changeAfterStartTime) {
            this.$set(this.formList[index], 'visible', true)
          }else {
            this.$set(this.formList[index], 'visible', false)
          }
        }else {
          if(projectDurationVO.changeAfterStartTimeLastMonth != projectDurationVO.changeAfterStartTime) {
            this.$set(this.formList[index], 'visible', true)
          }else {
            this.$set(this.formList[index], 'visible', false)
          }
        }
        return Promise.resolve()
      } else {
        return Promise.reject()
      }
    },
    /**
     * @description: 时间格式统一
     * @param {any} 时间
     * @return {string} 时间
     */
    timeMap(time) {
      if (typeof time === 'string') {
        return time
      } else {
        return time.format('YYYY-MM-DD')
      }
    },
    /**
     * @description: 表单组件改变
     * @param {string} keyName 组件字段名
     * @param {string} value 值
     * @return {void}
     */
    handleChange(keyName, value) {
      // 已组织观摩级别(隐藏显示已组织观摩内容)
      if (keyName === 'observingLevelId') {
        const index = this.formList.findIndex((el) => el.keyName === 'observingContent')
        if (index < 0) return
        const item = this.formList[index]
        if (value === '597645454968229890') {
          // 等于无
          item.visible = false
          this.$set(this.formList, index, item)
        } else {
          item.visible = true
          this.$set(this.formList, index, item)
          // 解决表单验证样式丢失
          this.$checkRequireItem()
        }
      }
      // 变更后开工日期改变
      if (keyName === 'changeAfterStartTime') {
        // 隐藏显示项目开工令/开工报告
        const index = this.formList.findIndex((el) => el.keyName === 'startWorkReportsFileList')
        if (index < 0) return
        const item = this.formList[index]
        if(!this.detail.projectDurationVO.changeAfterStartTimeLastMonth) {
          if ((value ?? '') !== '' && this.timeMap(value) === this.form.contractStartDate) {
            item.visible = false
            this.form.PerformanceInformaion = []
            this.$set(this.formList, index, item)
          } else {
            item.visible = true
            this.$set(this.formList, index, item)
          }
        }else {
          if ((value ?? '') !== '' && this.timeMap(value) === this.detail.projectDurationVO.changeAfterStartTimeLastMonth) {
            item.visible = false
            this.form.PerformanceInformaion = []
            this.$set(this.formList, index, item)
          } else {
            item.visible = true
            this.$set(this.formList, index, item)
          }
        }
        
        // 计算变更后工期
        this.form.changeAfterDuration = this.form.changeAfterFinishDate ? moment(this.form.changeAfterFinishDate).diff(value, 'day') : ''
        // 计算甲方确认原合同外顺延工期
        const contractDelayDuration = this.form.changeAfterDuration - this.form.contractDuration
        this.form.contractDelayDuration = contractDelayDuration > 0 ? contractDelayDuration : 0
        // 实际开工日期
        this.form.changeAfterStartTime && (this.form.actualStartTime = this.timeMap(this.form.changeAfterStartTime))
      }
      // 项目状态改变
      if (keyName === 'projectStatus') {
        // 隐藏显示实际竣工日期(项目状态为“竣工”时)
        const index = this.formList.findIndex((el) => el.keyName === 'actualFinishDate')
        if (index < 0) return
        const item = this.formList[index]
        if (value === 'MAINTENANCE_PERIOD') {
          item.disabled = true
          this.$set(this.formList, index, item)
          // 设置竣工情况
          this.form.completionSituation = '已竣工'
          let form = JSON.parse(JSON.stringify(this.form))
          setTimeout(()=> {
            this.form.actualFinishDate = form.actualFinishDate
          },2000)
        } else {
          item.disabled = true
          this.$set(this.formList, index, item)
          // 清空实际工期
          this.form.actualDuration = null
          // 清空实际延误工期
          this.form.actualDelayDuration = null
          // 清空工期延误率
          this.form.durationDelayRate = null

          this.form.actualFinishYear = null
          this.form.actualFinishQuarter = null
          this.form.actualFinishMonth = null

          // 设置竣工情况
          this.form.completionSituation = '未竣工'
          this.$refs.form.$refs.ruleForm.clearValidate(['actualFinishDate'])
        }
      }
      // 实际竣工日期改变
      if (keyName === 'actualFinishDate') {
        if (value ?? '' !== '') {
          // 计算实际工期
          this.form.actualDuration = this.moment(value).diff(moment(this.form.actualStartTime), 'day')
          // 计算实际竣工年度
          this.form.actualFinishYear = this.moment(value).format('YYYY')
          this.form.actualFinishDate = this.moment(value).format('YYYY-MM-DD')
          // 计算实际竣工季度
          this.form.actualFinishQuarter = Math.ceil(this.moment(value).format('MM') / 3)
          // 计算实际竣工月份
          this.form.actualFinishMonth = this.moment(value).format('MM')
          // 计算实际延误工期
          const actualDelayDuration = this.form.actualDuration - this.form.contractDuration
          this.form.actualDelayDuration = actualDelayDuration > 0 ? actualDelayDuration : 0
          // 计算工期延误率
          this.form.durationDelayRate = actualDelayDuration > 0 && this.form.contractDuration > 0 ? ((actualDelayDuration / this.form.contractDuration) * 100).toFixed(2) : 0
        }
      }
      // 累计专业工程暂估价发包额改变
      if (keyName === 'contractAmount' && this.form.contractAmount) {
        const contractRate = this.form.signingAmount / value
        this.form.contractRate = !isNaN(contractRate) && contractRate !== Infinity ? (contractRate * 100).toFixed(2) : 0
      }
      // 累计专业工程暂估价签约额改变
      if (keyName === 'signingAmount' && this.form.signingAmount) {
        const contractRate = value / this.form.contractAmount
        this.form.contractRate = !isNaN(contractRate) && contractRate !== Infinity ? (contractRate * 100).toFixed(2) : 0
      }
      this.durationConfirmRateHandler()
    },
    /**
     * @description: 表单值转换接口值
     * @param {string} key 表单对象key
     * @return {object} 接口对象
     */
    setObjData(key) {
      const obj = {}
      if (Object.prototype.toString.call(this.detail[key]) === '[object Object]') {
        Object.keys(this.detail[key]).forEach((el) => {
          // 格式化文件列表
          const whiteList = [
            {
              key: 'forecastFinishYear',
              value: 'Y'
            }
          ]
          const whiteItemArr = whiteList.filter((v) => v.key == el)
          if (whiteItemArr && whiteItemArr.length && typeof this.form[el] !== 'string') {
            this.form[el] = this.$dateFormat(this.form[el], whiteItemArr[0].value)
            if (whiteItemArr[0].value === 'M') {
              this.form[el] = this.form[el].slice(this.form[el].indexOf('-') + 1)
            }
          }
          // if (el == 'changeAfterStartTime' && typeof this.form[el] === 'object') {
          //   this.moment(new Date(this.form[el])).format('YYYY-MM-DD')
          // }
          obj[el] = this.form[el]
          if (el === 'durationConfirmRate') {
            obj[el] = this.form[el] === '/' ? '' : this.form[el]
          }
        })
      }
      return obj
    },
    /**
     * @description: 编辑
     * @param {string} auditStatus 提交状态
     * @return {void}
     */
    handleUpdate(auditStatus) {
      const vm = this
      if (auditStatus === 'SUBMITTED') {
        // this.$confirm({
        //   title: '提交确认',
        //   content: '请确认是否要提交？',
        //   onOk() {
            vm.$emit('update:submiting', true)
            vm.submitfun(auditStatus)
          // }
        // })
      } else {
        vm.submitfun(auditStatus)
      }
    },
    /**
     * @description: 提交函数
     * @param {string} auditStatus 提交状态
     * @return {void}
     */
    submitfun(auditStatus) {
      this.setProcessConfig = null
      this.submitApprovalConfirm(auditStatus === 'DRAFT' ? 6 : this.processConfig, (flag)=>{
        if(!flag) {
          this.$emit('update:submiting', false)
          return
        }
        projectDynamicInformation
                .edit({
                  auditStatus,
                  completionExpenseDTO: this.setObjData('completionExpenseVO'),
                  contractAmountConditionDTO: this.setObjData('contractAmountConditionVO'),
                  projectDurationDTO: this.setObjData('projectDurationVO'),
                  projectOverviewDTO: this.setObjData('projectOverviewVO'),
                  id: this.detail.id
                })
                .then(({ code, data: { id } }) => {
                  if (code === 200) {
                    this.$message.success(auditStatus === 'DRAFT' ? '保存成功' : '提交成功')
                    if (auditStatus === 'SUBMITTED') {
                      this.businessId = id
                      this.setProcessConfig = this.processConfig
                    }
                  }
                })
                .finally(() => {
                  this.$emit('update:submiting', false)
                })
      })

    },
    /**
     * @description: 提交
     * @param {void}
     * @return {void}
     */
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.handleUpdate('SUBMITTED')
        }
      })
    },
    /**
     * @description: 保存草稿
     * @param {void}
     * @return {void}
     */
    saveDrafts() {
      this.handleUpdate('DRAFT')
    }
  }
}
</script>
<style lang="less" scoped>
</style>

